package lsf.itcast.controller;

import lsf.itcast.domain.Permission;
import lsf.itcast.domain.Role;
import lsf.itcast.service.PermissionService;
import lsf.itcast.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;

    //查询所有角色
    @RequestMapping("/findAll.do")
    public ModelAndView findAll(){
        ModelAndView mv = new ModelAndView();
        List<Role> roles =roleService.findAll();
        mv.addObject("roleList",roles);
        mv.setViewName("role-list");
        return mv;
    }

    //新建角色
    @RequestMapping("/save.do")
    public String save(Role role){
       roleService.save(role);
    return "redirect:findAll.do";
    }

    @RequestMapping("/findRoleByIdAndAllPermission.do")
    public ModelAndView findRoleByIdAndAllPermission(@RequestParam(required = true,name = "id")String roleId){
    ModelAndView mv = new ModelAndView();
    //1.根据roleId查询的角色（注意：根据roleId查找用户，方便前台携带roleId到页面中，即隐藏的一个roleId;方便某个角色添加权限）
     Role role= roleService.findById(roleId);
    //2.根据查询到的角色，绑定权限（注意：需要排除中间表中已roleId绑定了permissionId,给只有roleId的绑定权限）
    List<Permission> permissions= permissionService.findOtherPermission(roleId);
    mv.addObject("role",role);
    mv.addObject("permissionList",permissions);
    mv.setViewName("role-permission-add");
    return mv;
    }

    @RequestMapping("/addPermissionToRole.do")
    public String addPermissionToRole(@RequestParam(required = true,name = "roleId")String roleId,@RequestParam(required = true,name = "ids")String[] permissionIds){
       roleService.addPermissionToRole(roleId,permissionIds);
        return "redirect:findAll.do";
    }
}
